<!--
 * @Author: MrDotYan 2564217790@qq.com
 * @Date: 2024-09-27 09:53:50
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-27 15:54:18
 * @FilePath: /midway-admin/webServerAdmin/src/views/user/personal/PasswordDialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form label-position="top" :model="modelValue" :rules="rules" ref="formRef">
      <el-form-item label="验证码" prop="code">
        <el-row style="width: 100%" :gutter="12">
          <el-col :span="17">
            <el-input v-model="modelValue.code"> </el-input>
          </el-col>
          <el-col :span="7">
            <div class="flex-end">
              <el-button @click="sendCaptcha" :disabled="timeCounter !== 60">
                <span>{{ timeCounter === 60 ? "发送验证码" : `${timeCounter}后重新发送` }}</span>
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="modelValue.password"></el-input>
      </el-form-item>
      <el-form-item label="重复密码" prop="newPassword">
        <el-input v-model="modelValue.newPassword"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { sendCaptchaEmail } from "@/api/modules/email";
import { useUserStore } from "@/stores/modules/user";
import { ElMessageBox, FormInstance } from "element-plus";
import { reactive } from "vue";
import { ResultEnum } from "@/enums/httpEnum";
import { ElMessage } from "element-plus";
import { ref } from "vue";
import { changePassword } from "@/api/modules/user";
import md5 from "md5";
import { logoutApi } from "@/api/modules/login";
import { LOGIN_URL } from "@/config";
import { useRouter } from "vue-router";

const formRef = ref<FormInstance>();
const userStore = useUserStore();
const modelValue = reactive({
  code: "",
  codeKey: "",
  password: "",
  newPassword: ""
});

function sendCaptcha() {
  if (userStore.userInfo.email && !timer.value) {
    sendCaptchaEmail({ email: userStore.userInfo!.email! }).then(r => {
      const { code, data, message } = r;
      if (code === ResultEnum.SUCCESS) {
        ElMessage.success("发送成功!");
        modelValue.codeKey = data.key;
        intervalSend();
      } else {
        ElMessage.error(message);
      }
    });
  }
}
const timer = ref<NodeJS.Timeout | null>(null);
const timeCounter = ref<number>(60);
function intervalSend() {
  timer.value = setTimeout(() => {
    timeCounter.value--;
    if (timeCounter.value <= 0) {
      clearTimeout(timer.value!);
      timeCounter.value = 60;
      timer.value = null;
    } else {
      intervalSend();
    }
  }, 1000);
}

function equalPassword(_rule, value, callback) {
  if (modelValue.password !== value) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
}

const rules = {
  code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }],
  newPassword: [
    { required: true, trigger: "blur", message: "请再次输入密码" },
    {
      required: true,
      validator: equalPassword,
      message: "两次密码不一致"
    }
  ]
};

const router = useRouter();
const logout = () => {
  ElMessageBox.confirm("修改密码后需要重新登录！", "温馨提示", {
    confirmButtonText: "确定",
    showCancelButton: false,
    type: "warning"
  }).then(async () => {
    // 1.执行退出登录接口
    const uid = userStore.userInfo.id;
    await logoutApi({ id: uid ?? "" });

    // 2.清除 Token
    userStore.setToken("");

    // 3.重定向到登陆页
    router.replace(LOGIN_URL);
    ElMessage.success("退出登录成功！");
  });
};

function submit() {
  formRef.value?.validate().then(valid => {
    if (valid) {
      changePassword(
        { id: userStore.userInfo.id! },
        {
          ...modelValue,
          password: md5(modelValue.password)
        }
      ).then(r => {
        const { code, data, message } = r;
        if (code === ResultEnum.SUCCESS) {
          userStore.setUserInfo(data);
          dialogVisible.value = false;
          ElMessage.success("修改成功！");
          logout();
        } else {
          ElMessage.error(message);
        }
      });
    }
  });
}

const dialogVisible = ref(false);
const openDialog = () => {
  dialogVisible.value = true;
};

defineExpose({ openDialog });
</script>

<style lang="scss" scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: 100%;
}
</style>
